<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\book\controller\member;

use app\book\base\BookMemberBase;

use app\book\model\BookOrder as BookOrderModel;

class Pay extends BookMemberBase{
    // 支付方式
    protected $tpye = '';
    // 支付文件
    protected $file = '';

    /**
     * TP初始化方法
     * @access public
     */
    public function _initialize(){
        parent::_initialize();
        $this->type = $this->request->param('type');
        $this->file = ROOT_PATH.'manniu'.DS.'plugins'.DS.'payment'.DS.$this->type.DS.$this->type.'.class.php';
    }

    /**
     * 充值页面
     * @access public
     * @return \think\Response
     */
    public function topup(){
    	return $this->getTemplate();
    }

    /**
     * 付款
     * @access public
     * @param string $type 		支付方式
     * @param int 	 $amount 	充值金额
     * @return mixed
     */
    public function payment($type = '', $amount = 0){
        /*
            支付流程
            1.获取用户提交的充值方式 与 充值金额
            2.判断充值接口是否存在
            3.随机生成订单号，如果订单号存在则提示订单生成失败，返回上页重新支付（超小概率情况下才会出现）
            4.入库订单信息
            5.获取支付类支付表单
            6.把得到的支付表单赋值给前端变量
            7.前端页面打开的页面跳转到第三方支付平台，如果是微信支付则不做跳转，直接显示二维码
            8.前端页面每5秒，轮询查询订单是否支付成功
            9.前端页面提供 支付成功按钮，以便用户自行确认是否支付成功
            
            10.跳转到支付结果页面
            11.如果支付成功则修改支付状态，并增加相应的虚拟币与赠送虚拟币
        */
    	$amount = (int)$amount;
    	if(empty($this->type) || !$amount){
    		$this->error('充值类型或金额未选择！');
    	}else if(!is_file($this->file)){
    		$this->error('无 '.$this->type.' 支付方式！');
    	}
    	// 导入具体的支付类文件                
        include_once $this->file;
        $type_class = '\\'.$this->type;
        $payment = new $type_class();

    	// 随机生成一个订单号
    	$order = [];
    	$order_sn = date("YmdHis").rand(100000,999999).rand(100000,999999);
    	$check = BookOrderModel::get(['order_sn'=>$order_sn]);
    	if($check){
    		$this->error('订单生成失败，请尝试重新支付！');
    	}

    	// 入库订单信息
		$order = BookOrderModel::create([
		    'uid' => $this->uid,
		    'order_sn' => $order_sn,
		    'type' => $this->type,
		    'order_amount' => $amount,
            'status' => 0
		]);

        if(!$order){
            $this->error('订单生成失败，请尝试重新支付！');
        }
        // 附加配置
        $config_value['notify_url'] = $this->request->domain().url('book/member.Pay/notifyUrl',['type'=>$this->type]);
        $config_value['return_url'] = $this->request->domain().url('book/member.Pay/returnUrl',['type'=>$this->type]);
        //微信JS支付
        if($this->type == 'weixin' && strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
            $code_str = $payment->getJSAPI($order, $config_value);
        }elseif ($this->type == 'weixin' && $this->request->isMobile()){
            $code_str = $payment->getH5($order, $config_value);
        }else{
            $code_str = $payment->getCode($order, $config_value);
        }
        $this->assign([
            'code_str'  => $code_str,
            'order'     => $order
        ]);
        return $this->getTemplate();
    }

    /**
     * 服务器异步通知页面
     * @access public
     * @param string $type      支付方式
     * @return mixed
     */
    public function notifyUrl(){
        if(!is_file($this->file)){
            // $this->error('无 '.$this->type.' 支付方式,如果支付方提示已充值成功请立即联系客服处理！',url('member/index/index'));
            echo 'fail';
            exit();
        }
        // 导入具体的支付类文件                
        include_once $this->file;
        $type_class = '\\'.$this->type;
        $payment = new $type_class();

        $payment->response();
        exit();
    }

    /**
     * 页面跳转同步通知页面
     * @access public
     * @param string $type      支付方式
     * @return mixed
     */
    public function returnUrl(){
        if(!is_file($this->file)){
            $this->error('无 '.$type.' 支付方式,如果支付方提示已充值成功请立即联系客服处理！', url('member/index/index'));
        }
        // 导入具体的支付类文件                
        include_once $this->file;
        $type_class = '\\'.$this->type;
        $payment = new $type_class();

        $result = $payment->respond2();

        $order = BookOrderModel::get(['order_sn' => $result['order_sn']]);

        $this->assign([
            'order' => $order,
            'status' => $result['status']
        ]);
        return $this->getTemplate();
    }
}
